<template>
	<view class="d-flex flex-column recharge-container" :style="{'min-height':windowHeight+'px'}">
		<u-toast ref="uToast"></u-toast>
		<view class="d-flex flex-row a-center j-sb top p-3">
			<view class="d-flex flex-column">
				<text class="d-flex text-black font-md3 font-weight mb">请选择充值金额</text>
				<text class="d-flex font-sm2 text-lightdark">1元=100看币</text>
			</view>
			<text class="d-flex top-right">账户余额：{{(userInfo.ml_coin||0)+(userInfo.give_coin||0)}}{{userInfo.coin_name}}</text>
		</view>
		<view class="d-flex flex-wrap">
			<view class="item-simulate" :style="{width:windowWidth+'px'}">
				<view class="d-flex list">
					<view v-for="(item,index) in showList" :key="index" :id="item.value" v-if="item.type!=2"
						class="box box-normal shadow-sm" :style="{width:(windowWidth/2)-20+'px','background-image': 'url('+item.bgtype+')'}" @tap.stop="onclick(index)"
						:class="{'box-active':cur_select_index==index}">
						<text v-if="item.classtext" class="position-absolute top-0 left-0 give" :style="{'background-image': 'linear-gradient(to right,'+item.classbgc+')', color: item.classcolor }">
							{{item.classtext}}
						</text>
						<view class="d-flex flex-column price j-center" :style="{color:item.amountcolor}">
							<view class="d-flex diyprice1 a-end j-center" :style="{color:item.amountcolor}">
								<view class="d-flex a-end" style="height: 40px;">
									<text class="d-flex" style="font-size: 18px;height: 32px;">￥</text>
								</view>
								<text>{{item.amount||0}}</text>
							</view>
							<text v-if="item.give_coin>0" class="diyprice2" :style="{color:item.amountcolor}">
								多送{{handleNum2(item.give_coin)}}元
							</text>
						</view>
						<view v-if="item.type==1" class="diycardfoot" :style="{'background-image': 'linear-gradient(to right,'+item.footcolor+')'}">
							<img style="width: 16px;height: 16px;margin-right: 5px;" :src="item.footicon" alt="" />
							{{handleGetNum(item.amount,item.give_coin)}}
						</view>
						<view v-if="item.foottext && item.type!==1" class="diycardfoot" :style="{'background-image': 'linear-gradient(to right,'+item.footcolor+')'}">
							{{item.foottext}}
						</view>
					</view>
				</view>
			</view>
			<view class="d-flex flex-column j-center px-3 mb-2">
				<text class="d-flex bottomTips text-lightdark">
					温馨提示:
				</text>
				<text class="d-flex bottomTips text-lightdark">
					1.充值成功后，获得的看币仅限在本小程序使用；
				</text>
				<text class="d-flex bottomTips text-lightdark">
					2.若发现充值未到账，请先确认你登录的账号与充值的账号是一致；
				</text>
				<text class="d-flex bottomTips text-lightdark">
					3.赠送看币存在有效期，充值赠送看币7天内有效；签到奖励看币3天内有效，消费时优先扣除赠送看币；
				</text>
				<text class="d-flex bottomTips text-lightdark">
					4.充值获得的看币或会员属于虚拟产品，充值成功后不支持退换；
				</text>
				<text class="d-flex bottomTips text-lightdark">
					5.未满18周岁的未成年人应在法定监护人指导、同意下进行充值并观看短剧；
				</text>
				<text class="d-flex bottomTips text-lightdark">
					6.个人中心只展示看币获得记录，消费记录暂不展示。
				</text>
			</view>
		</view>
		<view class="d-flex flex-column a-center j-center" :style="{width:windowWidth+'px'}">
			<u-button class="d-flex my-3"  color="linear-gradient(45deg, #ef8a3d, #fe5a40);" type="error" :ripple="true" shape="circle" size="default" 
			:custom-style="{width:windowWidth-30+'px',height:'45px'}"
				@click="toRecharge">
				<text class="font-md2">确认充值  {{showList[cur_select_index].amount?(showList[cur_select_index].amount+'元'):''}}</text>
			</u-button>
			<view class="d-flex" style="height: 50rpx;"></view>
		</view>
	</view>
</template>

<script>
	let that,intervalId,count;
	import {
		mapState
	} from 'vuex';
	import tools from "@/utils/tools.js"
	import config from '@/utils/config.js'
	import interfaces from '@/utils/interfaces.js'
	import {
		Decimal
	} from 'decimal.js'
	export default {
		data() {
			return {
			
				clickTime:null,
				showList: [],
				coin_name: uni.getStorageSync(config.coin_name) || '',
				unselect_db_color: '#FCECDE',
				cur_select_index: 0,
				select_db_color: '#E68B3E',
				db_biaoqian_tehui: "/static/video/video-cz-tehui.png",
				db_biaoqian_shouchong: "/static/video/video-cz-shouchong.png",
				db_biaoqian_chaozhi: "/static/video/video-cz-chaozhi.png",
			}
		},
		computed: {
			...mapState({
				userInfo: state => state.user.userInfo,
				statusBarHeight: state => state.layout.statusBarHeight,
				windowWidth: state => state.layout.windowWidth,
				windowHeight: state => state.layout.windowHeight,
				platform: state => state.layout.platform
			})
		},
		created() {
			that = this;
			this.$store.commit('mut_initLayout');
			tools.get_user_info_by_serve(that,(res)=>{});
			that.request({
				url: interfaces.goos_list,
				method: config.post,
				data: {
				},
				success: (r) => {
					that.showList = r.content.goods_list
					for (var i = 0; i < that.showList.length; i++) {
						if (that.showList[i].is_default === 1) {
							that.cur_select_index = i;
							break;
						}
					}
					console.log('商品列表', r)

				}
			})
		},
		methods: {
			handleGetNum(amount, give_coin) {
				if(!amount){ return}
				if (give_coin == 0) {
					return (new Decimal(amount).times(100).toFixed(2).replace(/\.?0+$/, '')) + '看币'
				} else {
					return (new Decimal(amount).times(100).toFixed(2).replace(/\.?0+$/, '')) + '+' + give_coin + '看币';
				}
			},
			handleNum2(num) {
				if (num) {
					let number = new Decimal(num);
					let result = number.times(0.01).toFixed(2);
					result = result.replace(/\.?0+$/, '');
					return result;
				}
			},
			getUUID() {
				const rx = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
				return `${+new Date()}_${rx}${rx}`
			},
			// #ifdef MP-TOUTIAO
			buy(recharge_goods_id) {
				
				console.log(155,!tt.canIUse('getOrderPayment'))
				if(!tt.canIUse('getOrderPayment')){
					return uni.showToast({title: '当前抖音App版本过低,请升级至最新版本',duration: 3000,icon: "none"});
				}
				let awaittime = 10
				let clickC = uni.getStorageSync('clickC') ? uni.getStorageSync('clickC') : 0 ;
				let releaseTime = uni.getStorageSync('releaseTime') ? uni.getStorageSync('releaseTime') : 0 ;
						
						
				if(Number(clickC)==0 ){
					uni.setStorageSync("releaseTime", new Date().getTime())
				}
				if(releaseTime != 0 && releaseTime + 60 * awaittime * 1000 < new Date().getTime()){
					uni.setStorageSync("clickC" , 0)
					uni.setStorageSync("releaseTime" , new Date().getTime())
				}
				
				if(Number(clickC)>=10 ){
					console.log("大于十次")
					if( releaseTime == 0 ){
							uni.setStorageSync("releaseTime", new Date().getTime())
							return uni.showToast({title: '请求过于频繁,请十分钟后再来!',duration: 3000,icon: "none"});
					}
					if(releaseTime != 0 && !(releaseTime + 60 * awaittime * 1000 < new Date().getTime()) ){
							return uni.showToast({title: '请求过于频繁,请十分钟后再来!',duration: 3000,icon: "none"});
					}
					
					if(releaseTime != 0 && releaseTime + 60 * awaittime * 1000 < new Date().getTime() ){
						uni.setStorageSync("clickC" , 0)
						uni.setStorageSync("releaseTime" , new Date().getTime())
					}
				}
				clickC = uni.getStorageSync('clickC') ? uni.getStorageSync('clickC') : 0 ;
				uni.setStorageSync("clickC", clickC + 1 )
				
		
				console.log(185,uni.getStorageSync('clickC'),uni.getStorageSync('releaseTime'))
				
				let {platform} = uni.getSystemInfoSync();
				platform = ['android', 'ios'].includes(platform) ? platform : 'android';
				console.log(platform);
				uni.showLoading({title: '加载中',mask:true});
				that.request({
					url: interfaces.buy,
					method: config.post,
					data: {
						"recharge_goods_id": recharge_goods_id
					},
					success: (r) => {
						
						console.log(165,r.content)
						if (r.code === config.SUCCESS) {
							
							let orderid = r.content.order_id
							let res = r.content || {};
							console.log('充值支付', r);
							let type,provider = 'toutiao';
							tt.requestOrder({
							   data: r.content.data , // 请勿在前端对data做任何处理
							   byteAuthorization: r.content.byteAuthorization, // 请勿在前端对byteAuthorization做任何处理
							   success: (res) => {
								   
							     console.log('200成功000', res);
							
								 tt.getOrderPayment({
								    orderId: res.orderId , // 请勿在前端对data做任何处理
								    success: (res) => {
								      console.log('200成功', res);	
									   uni.hideLoading();
									   uni.setStorageSync("clickC",0 )
										
									   
									   count = 0;
									   intervalId = setInterval(function() {
											if (count < 10) {
												that.getOrderStaus(orderid);
												count++;
											} else {
												uni.hideLoading();
												clearInterval(intervalId); // 清除定时器
											}
										}, 500);
									
								
								    },
								    fail: (err) => {
								      console.log("203",err.errNo==4);
									  uni.hideLoading();
									  uni.showToast({title: '支付失败',duration: 3000,icon: "none"});
								    },
								  });
								 
							   },
							   fail: (res) => {
								    uni.hideLoading();
							     console.log("2033",res)
								 uni.showToast({title: '获取订单信息失败',duration: 3000,icon: "none"});
							   },
							 });
						
						} else {
							uni.hideLoading();
							 console.log("2022")
							uni.showToast({title: '获取订单信息失败',duration: 3000,icon: "none"});
						}
					},
					fail: (err) => {
					  console.log("250",err)
					}
				})
			},
			// #endif
			// #ifdef MP-WEIXIN || MP-KUAISHOU
			// 微信充值支付
			buy(recharge_goods_id) {
				let awaittime = 10
				let clickC = uni.getStorageSync('clickC') ? uni.getStorageSync('clickC') : 0 ;
				let releaseTime = uni.getStorageSync('releaseTime') ? uni.getStorageSync('releaseTime') : 0 ;
				
				if(Number(clickC)==0 ){
					uni.setStorageSync("releaseTime", new Date().getTime())
				}
				if(releaseTime != 0 && releaseTime + 60 * awaittime * 1000 < new Date().getTime()){
					uni.setStorageSync("clickC" , 0)
					uni.setStorageSync("releaseTime" , new Date().getTime())
				}
				
				if(Number(clickC)>=10 ){
					console.log("大于十次")
					if( releaseTime == 0 ){
							uni.setStorageSync("releaseTime", new Date().getTime())
							return uni.showToast({title: '请求过于频繁,请十分钟后再来!',duration: 3000,icon: "none"});
					}
					if(releaseTime != 0 && !(releaseTime + 60 * awaittime * 1000 < new Date().getTime()) ){
							return uni.showToast({title: '请求过于频繁,请十分钟后再来!',duration: 3000,icon: "none"});
					}
					
					if(releaseTime != 0 && releaseTime + 60 * awaittime * 1000 < new Date().getTime() ){
						uni.setStorageSync("clickC" , 0)
						uni.setStorageSync("releaseTime" ,new Date().getTime() )
					}
				}
				clickC = uni.getStorageSync('clickC') ? uni.getStorageSync('clickC') : 0 ;
				uni.setStorageSync("clickC", clickC + 1 )
				console.log(340,uni.getStorageSync('clickC'),uni.getStorageSync('releaseTime'))
				
				let {platform} = uni.getSystemInfoSync();
				platform = ['android', 'ios'].includes(platform) ? platform : 'android';
				console.log(platform);
				uni.showLoading({title: '加载中',mask:true});
				that.request({
					url: this.platform == 'android' ? interfaces.buy : interfaces.buy_ios,
					method: config.post,
					data: {
						"recharge_goods_id": recharge_goods_id
					},
					success: (r) => {
						if (r.code === config.SUCCESS) {
							uni.hideLoading();
							let res = r.content || {};
							console.log('充值支付', r);
							if (this.platform == 'android') {
								that.request({
									url: interfaces.gei_sign,
									method: config.post,
									data: {
										signData: JSON.stringify({
											offerId: config.wxofferId,
											buyQuantity: res.amount,
											env: 0,
											platform: platform,
											currencyType: 'CNY',
											outTradeNo: res.order_id,
											attach: '123'
										}),
										mode: 'short_series_coin'
									},
									success: (rr) => {
										uni.hideLoading();
										if (rr.code === config.SUCCESS) {
											let resr = rr.content || {};
											console.log(resr);
											const SDKVersion = wx.getSystemInfoSync().SDKVersion;
											if (this.compareVersion(SDKVersion, '2.19.2') >= 0 || wx
												.canIUse('requestVirtualPayment')) {
												console.warn('微信虚拟支付');
												wx.requestVirtualPayment({
													signData: JSON.stringify({
														offerId: config.wxofferId,
														buyQuantity: res.amount,
														env: 0,
														platform: platform,
														currencyType: 'CNY',
														outTradeNo: res.order_id,
														attach: '123'
													}),
													paySig: resr.paySig,
													signature: resr.signature,
													mode: 'short_series_coin',
													success(virtualPayRes) {
														uni.setStorageSync("clickC",0 )
														console.log('11111虚拟支付成功',virtualPayRes);
														uni.showLoading({title: '查询订单中',mask: true});
														count = 0;
														intervalId = setInterval(function() {
														    if (count < 10) {
																that.getOrderStaus(res.order_id);
														        count++;
														    } else {
																uni.hideLoading();
														        clearInterval(intervalId); // 清除定时器
														    }
														}, 500);
													},
													fail({
														errMsg,
														errCode,
													}) {
														console.log(errCode);
														console.error(errMsg)
														uni.hideLoading();
														if(errCode==-2) return;
														if(errCode==-1){
															uni.showToast({title: '支付失败',duration: 3000,icon: "none"});
														}else{
															uni.showToast({title: '支付失败，错误码：'+errCode,duration: 3000,icon: "none"});
														}
													},
												})
											} else {
												uni.hideLoading();
												uni.showToast({title: '当前客户端版本不支持此支付，请升级微信版本',duration: 3000,icon: "none"});
												console.log('当前用户的客户端版本不支持 wx.requestVirtualPayment')
											}
										}
									},
								})
							}else{
								let provider = '';
								uni.getProvider({
									service: 'oauth',
									success: function(pres) {
										console.log(pres.provider)
										let type, provider;
										if (~pres.provider.indexOf('weixin')) {
											provider = 'wxpay';
										}
										// console.log({
										// 	provider,
										// 	timeStamp: res.timeStamp, //当前的时间
										// 	nonceStr: res.nonceStr, //随机字符串
										// 	package: res.package, //统一下单接口返回的 prepay_id 参数值
										// 	signType: res.signType, //签名算法
										// 	paySign: res.paySign});
										uni.requestPayment({
											provider,
											timeStamp: res.timeStamp, //当前的时间
											nonceStr: res.nonceStr, //随机字符串
											package: res.package, //统一下单接口返回的 prepay_id 参数值
											signType: res.signType, //签名算法
											paySign: res.paySign, //签名
											success(paymentRes) {
												uni.setStorageSync("clickC",0 )
												console.log('成功',paymentRes);
												count = 0;
												intervalId = setInterval(function() {
												    if (count < 10) {
														that.getOrderStaus(res.order_id);
												        count++;
												    } else {
														uni.hideLoading();
												        clearInterval(intervalId); // 清除定时器
												    }
												}, 500);
											},
											fail: (res) => {
												uni.hideLoading();
												uni.showToast({title: '支付失败',duration: 3000,icon: "none"});
												console.log('失败',res);
											},
										})
									}
								});
							}
						} else {
							uni.hideLoading();
							uni.showToast({title: '获取订单信息失败',duration: 3000,icon: "none"});
						}
					},
					fail: (err) => {
					  console.log("250",err)
					}
				})
			
			
			},
			// #endif
			getOrderStaus(orderID,checkorder=false){
				that.request({
					url: checkorder?interfaces.dycheckorder:interfaces.order_back,
					method: config.post,
					data: {
						order_id: orderID,
					},
					success: (orderRes) => {
						if (orderRes.code === config.SUCCESS) {
							console.warn('订单状态');
							console.log(orderRes);
							let orderResContent = orderRes.content || false;
							if(orderResContent){
								uni.hideLoading();
								tools.get_user_info_by_serve(that,(res)=>{});
								if(!checkorder){
									setTimeout(()=>{
										that.$refs.uToast.show({type: 'success',message:'感谢支持，充值成功！',duration:3500});
									},1000)
									if(intervalId){
										clearInterval(intervalId); // 清除定时器
									}
								}
							}
						}
					},
				})
			},
			compareVersion(_v1, _v2) {
				if (typeof _v1 !== 'string' || typeof _v2 !== 'string') return 0
				const v1 = _v1.split('.')
				const v2 = _v2.split('.')
				const len = Math.max(v1.length, v2.length)

				while (v1.length < len) {
					v1.push('0')
				}
				while (v2.length < len) {
					v2.push('0')
				}
				for (let i = 0; i < len; i++) {
					const num1 = parseInt(v1[i], 10)
					const num2 = parseInt(v2[i], 10)

					if (num1 > num2) {
						return 1
					} else if (num1 < num2) {
						return -1
					}
				}
				return 0
			},
			onClose() {
				this.$emit('closeCz', {});
			},
			onclick(index) {
				console.log(466,index)
				this.cur_select_index = index;
			},
			toRecharge(){
				let that=this
				clearTimeout(this.clickTime)
				this.clickTime = setTimeout(() => {
					  that.buy(that.showList[that.cur_select_index].recharge_goods_id);
				    }, 300);
			},
			get_db_color(index) {
				let color = index === this.cur_select_index ? this.select_db_color : this.unselect_db_color
				return color;
			},
			getBqSrc(type) {
				switch (type) {
					case config.cz_type.te_hui: {
						return this.db_biaoqian_tehui;
					}
					case config.cz_type.shou_chong: {
						return this.db_biaoqian_shouchong;
					}
					case config.cz_type.zheng_chang: {
						return '';
					}
					case config.cz_type.chao_zhi: {
						return this.db_biaoqian_chaozhi;
					}
				}

				return '';
			},
			isShowBq(type) {
				return type != config.cz_type.zheng_chang;
			},
			isShowDb(type) {
				return type != config.cz_type.chao_zhi;
			}
		}
	}
</script>

<style lang="scss" scoped>
	body{
		background-color: #f5f5f5;
	}
	.recharge-container {
	}
	.top {
		.top-left {
			font-size: 28rpx;
			color: #969696;
		}

		.top-right {
			font-size: 28rpx;
			color: #969696;
		}
	}

	.zc-item-bg {
		background: #FFFFFF;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		border: 4rpx solid #EDEDED;
	}

	.cz-item-bg {
		background: #FAEAC8;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		border: 4rpx solid #EDEDED;
	}

	.item-bg {
		background: #FCECDE;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		border: 4rpx solid #E56900;
	}

	.select-cz-item-bg {
		background: #FAEAC8;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		border: 4rpx solid #E56900;
	}
	
	.item-simulate {
		box-sizing: border-box;
		padding: 0px 12px;
	
		.list {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			align-items: flex-start;
	
			.box {
				height: 120px;
				cursor: default;
				background: #efefef;
				border: 1px solid #f5f5f5;
				border-radius: 15px;
				display: flex;
				position: relative;
				flex-direction: column;
				justify-content: flex-end !important;
				background-repeat: no-repeat;
				background-size: cover;
				padding: 0 !important;
				box-sizing: content-box;
				margin-bottom: 15px;
				align-items: center;
				overflow: hidden;
				.diyprice1{
					width: 100%;
					font-size: 26px;
					margin-top: 6px;
					color: #603013;
				}
				.diyprice2{
					width: 100%;
					display: flex;
					justify-content: center;
					font-size: 12px;
					line-height: 14px;
					margin-top: 4px;
					color: #603013;
				}
				.diycardfoot{
					width: 100%;
					height: 25px;
					display: flex;
					align-items: center;
					justify-content: center;
					position: absolute;
					bottom: 0;
					left: 0;
					font-size: 11px;
					font-weight: 600;
					color: #603013;
				}
				.tip {
					height: 22px;
					font-size: 12px;
					margin: 0;
					color: #bf891c;
				}
	
				.give {
					font-size: 12px;
					margin: 0;
					padding: 4px 16px;
					border-radius: 10px 0px;
					color: #fff;
					font-weight: 600;
				}
	
				.pointer {
					width: 50%;
					height: auto;
					position: absolute;
					bottom: 10px;
					right: -10px;
				}
	
				.price {
					position: absolute;
					top: 20px;
					width: 100%;
					height: 60px;
					font-size: 15px;
					font-weight: 600;
					line-height: 35px;
					margin: 0;
	
					.amountNum {
						font-size: 32px;
						font-style: normal;
						margin-bottom: 3px;
					}
				}
	
				.get {
					width: 100%;
					height: 28px;
					line-height: 28px;
					text-align: center;
					background: linear-gradient(180deg, #fff19d, #ff9e00);
					border-radius: 0 0 5px 5px;
					font-size: 14px;
					color: #583600;
					letter-spacing: 1px;
					font-weight: 500;
					margin: 0px;
				}
			}
	
			.box-normal {
				.price {
					color: #f76f21;
					.dd {
						font-size: 15px;
						color: #f95e5e;
					}
				}
				.get {
					background: #fff7e3;
					color: #bf891c;
				}
			}
	
	
			.box-active {
				border: 1px solid #f97d36;
			}
		}
	}
	
	.bottomTips {
		font-size: 24rpx;
		margin-bottom: 3px;
	}
</style>